package com.cn.nio.multinio;

import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

@Slf4j
//负责读取的selector
public class DoWorkThread extends Thread {

    Selector worksSelector;

    int id;

    public DoWorkThread() {
        this.id = NioMultiThread3.idMachine.getAndIncrement();
        try {
            worksSelector = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        try {
            String name = Thread.currentThread().getName();

            while (true) {

                if (worksSelector.select(1000) > 0) {

                    Set<SelectionKey> selectionKeys = worksSelector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        log.info(name + " 工作线程获取事件 ->  -> {} ", selectionKey);
                        if (selectionKey.isReadable()) {

                            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            try {
                                int read = socketChannel.read(byteBuffer);

                                byteBuffer.flip(); //读取bytebuffer之前要清理一下
                                CharBuffer decode = StandardCharsets.UTF_8.newDecoder().decode(byteBuffer);
                                log.info(Thread.currentThread().getName() + " 接收到请求-> " + decode.toString());

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            socketChannel.register(worksSelector, SelectionKey.OP_WRITE);

                        } else if (selectionKey.isWritable()) {

                            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            byteBuffer.put(
                                    String.valueOf(
                                            Thread.currentThread().getName() + " " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss").format(new Date())
                                    ).getBytes(StandardCharsets.UTF_8)
                            );

                            byteBuffer.flip();
                            socketChannel.write(byteBuffer);
                            socketChannel.close();

                        } else {
                            log.warn(Thread.currentThread().getName() + " 接收到特殊事件-> " + selectionKey);
                        }
                    }

                }

                //从boss 队列获取 建立好链接的。
                if (!NioMultiThread3.queue[id].isEmpty()) {
                    SocketChannel serverSocketChannel = NioMultiThread3.queue[id].poll();
                    if (serverSocketChannel != null) {
                        try {
//                            SocketChannel socketChannel = serverSocketChannel.accept();
//                            if (socketChannel != null) {
//                                socketChannel.configureBlocking(false);
//                                log.info("建立连接 -> {} ", socketChannel);
//                                socketChannel.register(worksSelector, SelectionKey.OP_READ); //从队列 获取 建立的连接，同时注册
//                            }

                            serverSocketChannel.register(worksSelector, SelectionKey.OP_READ); //从队列 获取 建立的连接，同时注册

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
